package com.megvii.koala.data.model;

import com.megvii.koala.data.UrlMaker;

/**
 * Created by linyue on 15/12/20.
 */
public class LoginModel implements UrlMaker
{
    public static final String KEY_USERNAME = "KEY_USERNAME";

    public static final String KEY_PASSWORD = "KEY_PASSWORD";

    public static final String KEY_SERVER = "KEY_SERVER";

    public static final String KEY_OFFLINE_SERVER = "KEY_OFFLINE_SERVER";

    public static final String URL_FLAG = "http";

    public static final String FS_FLAG = "file";

    private LoginModelListener listener = null;

    private String username;

    private String password;

    private String serverAddress;

    public void setListener(LoginModelListener listener)
    {
        this.listener = listener;
    }

    public void removeListener()
    {
        this.listener = null;
    }

    public String getServerAddress()
    {
        return serverAddress;
    }

    public void setServerAddress(String serverAddress)
    {
        String ori = this.serverAddress;
        this.serverAddress = serverAddress;
        if (listener != null)
        {
            if (ori == null && serverAddress != null || !ori.equals(serverAddress))
            {
                listener.onServerAddressChange(serverAddress);
            }
        }
    }

    public String getUsername()
    {
        return username;
    }

    public void setUsername(String username)
    {
        String ori = this.username;
        this.username = username;
        if (listener != null)
        {
            if (ori == null && username != null || !ori.equals(username))
            {
                listener.onUsernameChange(username);
            }
        }
    }

    public String getPassword()
    {
        return password;
    }

    public void setPassword(String password)
    {
        String ori = this.password;
        this.password = password;
        if (listener != null)
        {
            if (ori == null && password != null || !ori.equals(password))
            {
                listener.onPasswordChange(password);
            }
        }
    }

    @Override
    public String makeUrl(String relativeUrl)
    {
        if (relativeUrl == null || relativeUrl.isEmpty())
        {
            return null;
        }
        if (relativeUrl.startsWith(URL_FLAG) || relativeUrl.startsWith(FS_FLAG))
        {
            return relativeUrl;
        }
        else
        {
            return serverAddress + relativeUrl;
        }
    }

    public interface LoginModelListener
    {
        public void onUsernameChange(String username);

        public void onPasswordChange(String password);

        public void onServerAddressChange(String serverAddress);
    }
}
